package com.alipay.rebate.shop.service.admin.impl;

import com.alipay.rebate.shop.constants.PageFrameworkConstant;
import com.alipay.rebate.shop.core.AbstractService;
import com.alipay.rebate.shop.dao.mapper.PageFrameworkMapper;
import com.alipay.rebate.shop.model.PageFramework;
import com.alipay.rebate.shop.pojo.common.ResponseResult;
import com.alipay.rebate.shop.pojo.user.admin.PageFrameworkRequest;
import com.alipay.rebate.shop.pojo.user.admin.PageFrameworkResponse;
import com.alipay.rebate.shop.service.admin.AdminPageFrameworkService;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import javax.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class AdminPageFrameworkServiceImpl extends AbstractService<PageFramework> implements
    AdminPageFrameworkService {

  private Logger logger = LoggerFactory.getLogger(AdminPageFrameworkServiceImpl.class);
  @Resource
  private PageFrameworkMapper pageFrameworkMapper;

  @Override
  @Transactional
  public ResponseResult<Long> createOrUpdatePage(PageFrameworkRequest pageFrameworkRequest) {
    ResponseResult<Long> responseResult = new ResponseResult<>();

    if(pageFrameworkRequest.getPageId() == null){
      logger.debug("perform save action");
      // 如果页面id为空，那么进行保存
      long id = save(pageFrameworkRequest);
      responseResult.setData(id);
    }else{
      logger.debug("perform update action");
      // 如果页面id不为空，那么进行更新
      update(pageFrameworkRequest);
    }
    return responseResult;
  }

  @Transactional
  public long save(PageFrameworkRequest pageFrameworkRequest){
    // 插入页面
    PageFramework pageFramework = new PageFramework();
    pageFramework.setTitle(pageFrameworkRequest.getTitle());
    pageFramework.setIllustration(pageFrameworkRequest.getIllustration());
    pageFramework.setIsDefault(PageFrameworkConstant.NOT_DEFAULT);
    pageFramework.setIsCurrentUse(PageFrameworkConstant.NOT_CURRENT_USE);
    pageFramework.setUpdateTime(new Date());
    pageFramework.setPageModules(pageFrameworkRequest.getPageModules());
    pageFramework.setIsIndex(pageFrameworkRequest.getIsIndex());
    pageFramework.setStartColor(pageFrameworkRequest.getStartColor());
    pageFramework.setEndColor(pageFrameworkRequest.getEndColor());
    logger.debug("page frame work ready to save is : {}",pageFramework);
    pageFrameworkMapper.insertSelective(pageFramework);
    return pageFramework.getPageId();
//    logger.debug("page module ready to save is : {}",pageFrameworkRequest.getPageModules());

    // 插入模板
//    Optional.ofNullable(pageFrameworkRequest.getPageModules()).ifPresent(pageModules -> {
//      logger.debug("page frame work is : {}",pageFramework);
//      pageModules.forEach(pageModule -> {
//        pageModule.setPageId(pageFramework.getPageId());
//        pageModule.setCreateTime(new Date());
//        // 将moduleJson 转成字符串存进数据库
//        setJsonFromModuleJsonObject(pageModule);
//      });
//      pageModuleMapper.insertPageModuleList(pageModules);
//    });
  }

  @Transactional
  public void update(PageFrameworkRequest pageFrameworkRequest){

    // 更新页面
    PageFramework pageFramework = new PageFramework();
    pageFramework.setPageId(pageFrameworkRequest.getPageId());
    pageFramework.setTitle(pageFrameworkRequest.getTitle());
    pageFramework.setIllustration(pageFrameworkRequest.getIllustration());
    pageFramework.setUpdateTime(new Date(System.currentTimeMillis()));
    pageFramework.setPageModules(pageFrameworkRequest.getPageModules());
    pageFramework.setIsIndex(pageFrameworkRequest.getIsIndex());
    pageFramework.setStartColor(pageFrameworkRequest.getStartColor());
    pageFramework.setEndColor(pageFrameworkRequest.getEndColor());
    logger.debug("page frame work ready to update is : {}",pageFramework);
    pageFrameworkMapper.updateByPrimaryKeySelective(pageFramework);

    // 根据页面id删除旧的模板
    logger.debug("deleting old modules");
//    pageModuleMapper.deleteByPagePrimaryKey(pageFramework.getPageId());

    // 插入新的模板
//    logger.debug("page module ready to save is : {}",pageFrameworkRequest.getPageModules());
//    Optional.ofNullable(pageFrameworkRequest.getPageModules()).ifPresent(pageModules -> {
//      pageModules.forEach(pageModule -> {
//        pageModule.setCreateTime(new Date());
//        // 将moduleJson 转成字符串存进数据库
//        setJsonFromModuleJsonObject(pageModule);
//      });
//      pageModuleMapper.insertPageModuleList(pageModules);
//    });
  }

  @Override
  @Transactional
  public ResponseResult<Integer> updatePageFrameWork(PageFramework pageFramework) {
    // 获取当前默认模板
    PageFramework defaultPageFramework = pageFrameworkMapper.selectDefaultPageFramework();
    ResponseResult<Integer> responseResult = new ResponseResult<>();
    // 如果设置的默认模板和当前默认模板相同，那么直接返回
    if(defaultPageFramework != null
        && defaultPageFramework.getPageId().equals(pageFramework.getPageId())
        && PageFrameworkConstant.IS_DEFAULT.equals(pageFramework.getIsDefault())
    ){
      return responseResult;
    }
    if(defaultPageFramework != null &&
        PageFrameworkConstant.IS_DEFAULT.equals(pageFramework.getIsDefault())){
      // 将上一个默认页面设置非默认
      PageFramework p = new PageFramework();
      p.setPageId(defaultPageFramework.getPageId());
      p.setIsDefault(PageFrameworkConstant.NOT_DEFAULT);
      pageFrameworkMapper.updateByPrimaryKeySelective(p);
    }

    // 设置默认模板
    int result = pageFrameworkMapper.updateByPrimaryKeySelective(pageFramework);
    responseResult.setData(result);
    return responseResult;
  }

  @Transactional
  public ResponseResult<List<PageFrameworkResponse>> selectAllPageFramework(){

    ResponseResult<List<PageFrameworkResponse>> responseResult = new ResponseResult<>();
    // 查询所有的页面模板
    List<PageFramework> pageFrameworks = pageFrameworkMapper.selectAll();
    logger.debug("All pageFromeworks is: {}",pageFrameworks);
    List<PageFrameworkResponse> pageFrameworkResponses = new ArrayList<>();
    Optional.ofNullable(pageFrameworks).ifPresent(pageFrameworkList -> {
      pageFrameworks.forEach(pageFramework -> {
        PageFrameworkResponse pageFrameworkResponse = new PageFrameworkResponse();
        converPageFrameworkToResponse(pageFrameworkResponse,pageFramework);
        logger.debug("pageFrameworkResponse is: {}",pageFrameworkResponse);
//        List<PageModule> pageModules = pageModuleMapper.selectByPagePrimaryKey(pageFramework.getPageId());
//        handlePageModuleList(pageModules);
//        pageFrameworkResponse.setPageModules(pageModules);
        pageFrameworkResponses.add(pageFrameworkResponse);
      });
    });
    responseResult.setData(pageFrameworkResponses);
    return responseResult;
  }

  @Override
  @Transactional
  public ResponseResult<PageFrameworkResponse> selectPageFrameworkByPageId(Long pageId){

    ResponseResult<PageFrameworkResponse> responseResult = new ResponseResult<>();
    // 查询所有的页面模板
    PageFramework pageFramework = pageFrameworkMapper.selectByPrimaryKey(pageId);
    logger.debug("pageFromeworks is: {}",pageFramework);
    PageFrameworkResponse pageFrameworkResponse = null;
    if(pageFramework != null){
      pageFrameworkResponse = new PageFrameworkResponse();
      converPageFrameworkToResponse(pageFrameworkResponse,pageFramework);
      logger.debug("PageFramework is: {}",pageFrameworkResponse);
//      List<PageModule> pageModules = pageModuleMapper.selectByPagePrimaryKey(pageFramework.getPageId());
//      handlePageModuleList(pageModules);
//      pageFrameworkResponse.setPageModules(pageModules);
    }
    responseResult.setData(pageFrameworkResponse);
    return responseResult;
  }

  @Override
  public List<PageFramework> selectUsePageFramework(Integer isUse) {
    return pageFrameworkMapper.selectUsePageFramework(isUse);
  }

  @Override
  public List<PageFramework> selectAllByType(Integer isIndex) {
    return pageFrameworkMapper.selectAllByType(isIndex);
  }

  @Override
  public int createPageIndex(PageFrameworkRequest pageFrameworkRequest) {
    PageFramework pageFramework = new PageFramework();
    if (pageFrameworkRequest.getTitle() == null){
      pageFramework.setTitle("底部导航栏");
    }
    pageFramework.setPageModules(pageFrameworkRequest.getPageModules());
    Date date = new Date();
    pageFramework.setCreateTime(date);
    pageFramework.setPageId(pageFrameworkRequest.getPageId());
    pageFramework.setUpdateTime(date);
    pageFramework.setIsDefault(0);
    pageFramework.setIllustration("");
    pageFramework.setIsCurrentUse(0);
    pageFramework.setIsIndex(0);
    pageFramework.setIsUpdate(0);
    pageFramework.setStartColor(pageFrameworkRequest.getStartColor());
    pageFramework.setEndColor(pageFrameworkRequest.getEndColor());
    int result = pageFrameworkMapper.insertSelective(pageFramework);
    return result;
  }

  @Override
  public List<PageFramework> selectPageIndex() {
    List<PageFramework> pageFrameworks = pageFrameworkMapper.selectPgeIndexList();
    return pageFrameworks;
  }

  @Override
  public int updatePageIndex(PageFrameworkRequest pageFrameworkRequest) {
    PageFramework pageFramework = new PageFramework();
    pageFramework.setPageModules(pageFrameworkRequest.getPageModules());
    pageFramework.setPageId(pageFrameworkRequest.getPageId());
    logger.debug("pageFrameWork is : {}",pageFramework);
    int result = pageFrameworkMapper.updatePageIndex(pageFramework);
    return result;
  }

  private PageFrameworkResponse converPageFrameworkToResponse(
      PageFrameworkResponse pageFrameworkResponse,
      PageFramework pageFramework){
    pageFrameworkResponse.setPageId(pageFramework.getPageId());
    pageFrameworkResponse.setTitle(pageFramework.getTitle());
    pageFrameworkResponse.setIllustration(pageFramework.getIllustration());
    pageFrameworkResponse.setCreateTime(pageFramework.getCreateTime());
    pageFrameworkResponse.setUpdateTime(pageFramework.getUpdateTime());
    pageFrameworkResponse.setIsDefault(pageFramework.getIsDefault());
    pageFrameworkResponse.setIsCurrentUse(pageFramework.getIsCurrentUse());
    pageFrameworkResponse.setPageModules(pageFramework.getPageModules());
    pageFrameworkResponse.setStartColor(pageFramework.getStartColor());
    pageFrameworkResponse.setEndColor(pageFramework.getEndColor());
    return pageFrameworkResponse;
  }
}
